//
//  SHDataProvider.swift
//  ServiceHelper
//
//  Created by Stan Wu on 15/4/7.
//  Copyright (c) 2015 Stan Wu. All rights reserved.
//
import UIKit

///**
// *  设备版本
// *
// */
//extension UIDevice {
//    
//    var modelName: String {
//        var systemInfo = utsname()
//        uname(&systemInfo)
//        let machineMirror = Mirror(reflecting: systemInfo.machine)
//        let identifier = machineMirror.children.reduce("") { identifier, element in
//            guard let value = element.value as? Int8 where value != 0 else { return identifier }
//            return identifier + String(UnicodeScalar(UInt8(value)))
//        }
//        
//        switch identifier {
//        case "iPod5,1":                                 return "iPod Touch 5"
//        case "iPod7,1":                                 return "iPod Touch 6"
//        case "iPhone3,1", "iPhone3,2", "iPhone3,3":     return "iPhone 4"
//        case "iPhone4,1":                               return "iPhone 4s"
//        case "iPhone5,1", "iPhone5,2":                  return "iPhone 5"
//        case "iPhone5,3", "iPhone5,4":                  return "iPhone 5c"
//        case "iPhone6,1", "iPhone6,2":                  return "iPhone 5s"
//        case "iPhone7,2":                               return "iPhone 6"
//        case "iPhone7,1":                               return "iPhone 6 Plus"
//        case "iPhone8,1":                               return "iPhone 6s"
//        case "iPhone8,2":                               return "iPhone 6s Plus"
//        case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4":return "iPad 2"
//        case "iPad3,1", "iPad3,2", "iPad3,3":           return "iPad 3"
//        case "iPad3,4", "iPad3,5", "iPad3,6":           return "iPad 4"
//        case "iPad4,1", "iPad4,2", "iPad4,3":           return "iPad Air"
//        case "iPad5,3", "iPad5,4":                      return "iPad Air 2"
//        case "iPad2,5", "iPad2,6", "iPad2,7":           return "iPad Mini"
//        case "iPad4,4", "iPad4,5", "iPad4,6":           return "iPad Mini 2"
//        case "iPad4,7", "iPad4,8", "iPad4,9":           return "iPad Mini 3"
//        case "iPad5,1", "iPad5,2":                      return "iPad Mini 4"
//        case "iPad6,7", "iPad6,8":                      return "iPad Pro"
//        case "AppleTV5,3":                              return "Apple TV"
//        case "i386", "x86_64":                          return "Simulator"
//        default:                                        return identifier
//        }
//    }
//    
//}

class SHDataProvider: NSObject {
    //  MARK: - APIs
    class func login(parameters: NSDictionary?) -> NSDictionary?{
        var dictNew:NSMutableDictionary
        
        if let param = parameters{
            dictNew = NSMutableDictionary(dictionary: param)
        }else{
            dictNew = NSMutableDictionary()
        }
        
        let strPwd = dictNew.objectForKey("password") as! String?

        if let pwd = strPwd{
            let mosaic = "\(pwd)mosaic"
            let strPwdMD5 = mosaic.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)?.MD5String().lowercaseString
            
            dictNew.setObject(strPwdMD5!, forKey: "password")
        }
        
        NSUserDefaults.standardUserDefaults().removeObjectForKey("access_token")
        
        let dictR = getData("login", parameters: dictNew)
        
        if let result = dictR{
            if let userInfo = result.objectForKey("data") as! NSDictionary?{
                let access_token = userInfo.objectForKey("access_token") as! String
                NSUserDefaults.standardUserDefaults().setObject(access_token, forKey: "access_token")
                NSUserDefaults.standardUserDefaults().setObject(userInfo, forKey: "UserInfo")
            }
        }

        return dictR
    }
    
    class func getDealerOrderList(parameters: NSDictionary?) -> NSDictionary?{
        return SHDataProvider.getData("getDealerOrderList", parameters: parameters)
    }
    
    class func acceptOrder(parameters: NSDictionary?) -> NSDictionary?{
        return SHDataProvider.getData("acceptOrder", parameters: parameters)
    }
    
    class func refuseOrder(parameters: NSDictionary?) -> NSDictionary?{
        return SHDataProvider.getData("refuseOrder", parameters: parameters)
    }
    
    class func adjustOrder(parameters: NSDictionary?) -> NSDictionary?{
        return SHDataProvider.getData("adjustOrder", parameters: parameters)
    }
    
    //获取订单详情
    class func getOrderDetail(parameters: NSDictionary?) -> NSDictionary?{
        return SHDataProvider.getData("getOrderDetail", parameters: parameters)
    }
    
    class func getNewOrderDetail(parameters: NSDictionary?) -> NSDictionary? {
        return SHDataProvider.getNewData("getNewOrderDetail", parameters: parameters)
    }
    
    //获取工单
    class func getWorkOrderInfo(parameters: NSDictionary) -> NSDictionary? {
        return SHDataProvider.getNewData("getWorkOrderInfo", parameters: parameters)
    }
    
    //选取送车员
    class func shopSelectedSendCarPerson(parameters: NSDictionary?) -> NSDictionary?{
        return SHDataProvider.getData("shopSelectedSendCarPerson", parameters: parameters)
    }
    
    //选取取车员
    class func shopSelectedGetCarPerson(parameters: NSDictionary?) -> NSDictionary?{
        return SHDataProvider.getData("shopSelectedGetCarPerson", parameters: parameters)
    }
    
    //获取取车员列表
    class func getDealerPersonList(parameters: NSDictionary?) -> NSDictionary?{
        return SHDataProvider.getData("getDealerPersonList", parameters: parameters)
    }
    //确认订单
    class func confimOrder(parameters: NSDictionary?) -> NSDictionary?{
        return SHDataProvider.getData("confimOrder", parameters: parameters)
    }
    //开始服务
    class func startService(parameters: NSDictionary?) -> NSDictionary?{
        return SHDataProvider.getData("startService", parameters: parameters)
    }
    //服务完成
    class func endService(parameters: NSDictionary?) -> NSDictionary?{
        return SHDataProvider.getData("endService", parameters: parameters)
    }
    
    //确认用户已付款
    class func alreadyPay(parameters: NSDictionary?) -> NSDictionary?{
        return SHDataProvider.getData("alreadyPay", parameters: parameters)
    }
    
    
    //获取4S店通知列表
    class func getDealerNoticeList(parameters: NSDictionary?) -> NSDictionary?{
        return SHDataProvider.getData("getDealerNoticeList", parameters: parameters)
    }
    
    
    //获取4S店通知列表
    class func cancleOrder(parameters: NSDictionary?) -> NSDictionary?{
        return SHDataProvider.getData("cancleOrder", parameters: parameters)
    }
    
    //待处理订单数
    class func getWaitDealsum(parameters: NSDictionary?) -> NSDictionary?{
        return SHDataProvider.getData("getWaitDealsum", parameters: parameters)
    }
    
    
    //待处理订单数
    class func bindDeviceToken(parameters: NSDictionary?) -> NSDictionary?{
        return SHDataProvider.getData("bindDeviceToken", parameters: parameters)
    }
    
    //获取OSS远程验证
    class func getCredentials(parameters: NSDictionary?) -> NSDictionary?{
        return SHDataProvider.getData("getCredentials", parameters: parameters)
    }
    
    
    // MARK: - Utils Functions
    class func getDealerID() -> String!{
        if let userInfo = getUserInfo(){
            if let dealerID = userInfo.objectForKey("belong_to_dealer") as? String{
                return dealerID
            }else{
                return "0"
            }
        }else{
            return "0"
        }
    }
    
    class func getUserInfo() -> NSDictionary?{
        return NSUserDefaults.standardUserDefaults().objectForKey("UserInfo") as! NSDictionary?
    }
    
    // MARK: - Basic Functions
    //处理参数 dictionary 拼接参数
    class func paramString(param:NSDictionary) -> String{
        let requestTime = String(format: "%.0lf", NSDate().timeIntervalSince1970)
        let dictParamNew:NSMutableDictionary = NSMutableDictionary(dictionary: param)
        dictParamNew.setObject(requestTime, forKey: "request_time")

        let version = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String
        dictParamNew.setObject(version, forKey: "app_version")

        dictParamNew.setValue(UIDevice.currentDevice().systemVersion, forKey: "os")
        dictParamNew.setValue(getDeviceVersion(), forKey: "setup")
        
        let access_token = NSUserDefaults.standardUserDefaults().objectForKey("access_token") as! String?

        if let at = access_token {
            dictParamNew.setObject(at, forKey: "access_token")
        }else{
            dictParamNew.setObject(clientID(), forKey: "client_id")
            dictParamNew.setObject(String.UUIDString(), forKey: "device_id")
        }
        
        // concat parameters
        let str:NSMutableString = NSMutableString()
        
        for i in 0 ..< dictParamNew.allKeys.count{
            let key = dictParamNew.allKeys[i] as! String
            str.appendString("&")
            str.appendFormat("%@=%@", key,dictParamNew.objectForKey(key) as! String!)
        }

        //add sign
        str.appendFormat("&sign=%@", sign(dictParamNew))
        
        return str as String;
    }
    //加密规则
    class func sign(param:NSDictionary) -> String{
        
        
        let keyItem1: String = clientID().dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!.MD5String()
        let keyItem2: String = String.UUIDString().dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!.MD5String()
        
        let requestTime = param.objectForKey("request_time") as! String!
        let keyItem3 = requestTime.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!.MD5String()

        let key = "\(keyItem1)\(keyItem2)\(keyItem3)".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!.MD5String()
        
        //real_key
        let real_key = key.HMACSHA1StringWithKey(clientSecret())

        //data
        let dictNew = NSMutableDictionary(dictionary: param)

        
        let data: String = SHDataProvider.sortParam(dictNew)

        
        
        //sign
        let sign = data.HMACSHA1StringWithKey(real_key)
        
        return sign
    }


    //对参数字典进行排序
    class func sortParam(param: NSDictionary) -> String{
        let strMul = NSMutableString()

        let keys = param.allKeys as! [String]

        let sortedArray = keys.sort { (obj1: String, obj2: String) -> Bool in
            let result = obj1.compare(obj2, options: NSStringCompareOptions.NumericSearch)
            if result != NSComparisonResult.OrderedDescending{
                return true
            }else{
                return false
            }
        }

        for key in sortedArray {
            strMul.appendString("\(key)=\(param.objectForKey(key)!)")
        }
        
        return strMul as String;
    }
    

    
    //系统型号
    class func clientID() -> String{
        return "haima_ios"
    }

    //盐
    class func clientSecret() -> String{
        return "fa0bf1259c544a453c16c21233993308be10b19e";
    }
    
    class func getNewData(api: String,parameters: NSDictionary?) -> NSDictionary?{
        let dicAPI = NSDictionary(contentsOfFile: "api.plist".bundlePath()) as NSDictionary!
        //\\
//        let appdelegate: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
        
        let baseURL = dicAPI.objectForKey("baseURLJava") as! String!
        let url = NSURL(string: "\(baseURL)\(dicAPI.objectForKey(api)!)")!
        
        let request: NSMutableURLRequest = NSMutableURLRequest(URL: url, cachePolicy: NSURLRequestCachePolicy.UseProtocolCachePolicy, timeoutInterval: 20)
        request.HTTPMethod = "POST"
        
        request.setValue("gzip", forHTTPHeaderField: "Accept-Encoding")
        
        var real_param = NSDictionary()
        
        if let param = parameters{
            real_param = param
        }
        
        let pLast = paramString(real_param)
        
        print("\(url)?\(pLast)");
        
        request.HTTPBody = pLast.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
        
        var data: NSData?,error: NSError?,content: String?,dict: NSDictionary?
        let response: AutoreleasingUnsafeMutablePointer<NSURLResponse?> = nil
        
        
        do {
            data = try NSURLConnection.sendSynchronousRequest(request, returningResponse: response)
        } catch let error1 as NSError {
            error = error1
            data = nil
        }
        
        //  get
        
        if let er = error{
            NSLog("API Error:%@", er)
        }
        
        if let d = data{
            content = NSString(data: d, encoding: NSUTF8StringEncoding) as? String
            do{
                dict = try NSJSONSerialization.JSONObjectWithData(d, options: NSJSONReadingOptions()) as? NSDictionary
            }catch _{
                
            }
            
        }
        
        
        
        if let result = dict
        {
            //            print(result)
            SWUtils.RunOnMainThread({ () -> Void in
//                let code = (result.objectForKey("code") as! NSNumber).integerValue
                
                let code = result.objectForKey("code")?.intValue
                
//                NSLog("response code:%d",code)
                
                if code==10006{
                    NSNotificationCenter.defaultCenter().postNotificationName("AccessTokenInvalidLongTime", object: nil)
                }else if code == 10007{
                    NSNotificationCenter.defaultCenter().postNotificationName("AccessTokenInvalid", object: nil)
                }
            })
            
            return result;
        }else if let c = content{
            dict = ["code":"0","error":c]
        }
        
        return dict;
    }
    
    class func getDeviceVersion () -> String? {
        let name = UnsafeMutablePointer<utsname>.alloc(1)
        uname(name)
        let machine = withUnsafePointer(&name.memory.machine, { (ptr) -> String? in
            
            let int8Ptr = unsafeBitCast(ptr, UnsafePointer<CChar>.self)
            return String.fromCString(int8Ptr)
        })
        name.dealloc(1)
        if let deviceString = machine {
            switch deviceString {
            //iPhone
            case "iPod5,1":                                 return "iPod Touch 5"
            case "iPod7,1":                                 return "iPod Touch 6"
            case "iPhone3,1", "iPhone3,2", "iPhone3,3":     return "iPhone 4"
            case "iPhone4,1":                               return "iPhone 4s"
            case "iPhone5,1", "iPhone5,2":                  return "iPhone 5"
            case "iPhone5,3", "iPhone5,4":                  return "iPhone 5c"
            case "iPhone6,1", "iPhone6,2":                  return "iPhone 5s"
            case "iPhone7,2":                               return "iPhone 6"
            case "iPhone7,1":                               return "iPhone 6 Plus"
            case "iPhone8,1":                               return "iPhone 6s"
            case "iPhone8,2":                               return "iPhone 6s Plus"
            case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4":return "iPad 2"
            case "iPad3,1", "iPad3,2", "iPad3,3":           return "iPad 3"
            case "iPad3,4", "iPad3,5", "iPad3,6":           return "iPad 4"
            case "iPad4,1", "iPad4,2", "iPad4,3":           return "iPad Air"
            case "iPad5,3", "iPad5,4":                      return "iPad Air 2"
            case "iPad2,5", "iPad2,6", "iPad2,7":           return "iPad Mini"
            case "iPad4,4", "iPad4,5", "iPad4,6":           return "iPad Mini 2"
            case "iPad4,7", "iPad4,8", "iPad4,9":           return "iPad Mini 3"
            case "iPad5,1", "iPad5,2":                      return "iPad Mini 4"
            case "iPad6,7", "iPad6,8":                      return "iPad Pro"
            case "AppleTV5,3":                              return "Apple TV"
            case "i386", "x86_64":                          return "Simulator"
            default:                                        return deviceString
            }
        } else {
            return nil
        }
    }
    //数据请求方法
    class func getData(api: String,parameters: NSDictionary?) -> NSDictionary?{
        let dicAPI = NSDictionary(contentsOfFile: "api.plist".bundlePath()) as NSDictionary!

        let appdelegate: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
        
        let baseURL = dicAPI.objectForKey(appdelegate.isInTestStatus() ? "preBaseURL1" : "baseURL") as! String!
        let url = NSURL(string: "\(baseURL)\(dicAPI.objectForKey(api)!)")!

        let request: NSMutableURLRequest = NSMutableURLRequest(URL: url, cachePolicy: NSURLRequestCachePolicy.UseProtocolCachePolicy, timeoutInterval: 20)
        request.HTTPMethod = "POST"
        
        request.setValue("gzip", forHTTPHeaderField: "Accept-Encoding")

        var real_param = NSDictionary()

        if let param = parameters{
            real_param = param
        }
        
        let pLast = paramString(real_param)
        
        print("\(url)?\(pLast)");
        
        request.HTTPBody = pLast.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)

        var data: NSData?,error: NSError?,content: String?,dict: NSDictionary?
        let response: AutoreleasingUnsafeMutablePointer<NSURLResponse?> = nil
        do {
            data = try NSURLConnection.sendSynchronousRequest(request, returningResponse: response)
        } catch let error1 as NSError {
            error = error1
            data = nil
        }
        
        if let er = error{
            NSLog("API Error:%@", er)
        }
        
        if let d = data{
            content = NSString(data: d, encoding: NSUTF8StringEncoding) as? String
            do{
                dict = try NSJSONSerialization.JSONObjectWithData(d, options: NSJSONReadingOptions()) as? NSDictionary
            }catch _{
                
            }
            
        }
        

        
        if let result = dict
        {
//            print(result)
            SWUtils.RunOnMainThread({ () -> Void in
                let code = (result.objectForKey("code") as! NSNumber).integerValue
 
                NSLog("response code:%d",code)
                
                if code==10006{
                    //长时间未登录
                    NSNotificationCenter.defaultCenter().postNotificationName("AccessTokenInvalidLongTime", object: nil)
                }else if code == 10007{
                    //登录不可用
                    NSNotificationCenter.defaultCenter().postNotificationName("AccessTokenInvalid", object: nil)
                }
            })

            return result;
        }else if let c = content{
            dict = ["code":"0","error":c]
        }
        
        return dict;
    }
    
   
}
